<?php
namespace app\appadmin\controller\v1;
use app\app\Appbase;
use app\common\model\Shop as ShopModel;
use base\pay\WxApi;

class Shop extends Appbase 
{
	
	/**
     * 获取店铺列表
     * /appadmin/v1/Shop/shopLists
     * 需要登录
     * @is_need_login true
     * @method post
     */
    public function shopLists($type=1){
    	$shopId = request()->shopId;
    	$identity = request()->identity;
        try {
            $model = new ShopModel();
            $model = $model-> where("is_del",0);
            $model = $model-> where("status",1);
            $model = $model-> where("is_enable",1);
            if($identity!=1){
	       		$model = $model->where("id",$shopId);
	        }
            $model = $model-> field(" name as label , id as value ");
            $result = $model->select()->toArray();
            if($identity==1 && $type !=2) {
            	array_unshift($result,["label"=>"所有门店","value"=>"-1"]);    
            }
            return $this->ReSucess($result);	
        } catch (\Exception $e) {
            return $this->ReError($e->getMessage());
        }
    }
    
    /**
     * 获取店铺员工列表
     * /appadmin/v1/Shop/shopStaffLists
     * 需要登录
     * @is_need_login true
     * @method post
     */
    public function shopStaffLists($shop_id){
    	$identity = request()->identity;
    	$uid = request()->userId;
        try {
            $model = model('ShopStaff');
            $model = $model->where("shop_id",$shop_id);
            $model = $model-> where("is_del",0);
            $model = $model-> where("status",1);
            if($identity==3){
            	$model = $model-> where("id",$uid);
            }
            $model = $model-> field("gh,work_type,name,id");
            $result = $model->select()->toArray();
            if( $identity != 3 ) {
            	array_unshift($result,["name"=>"所有员工","id"=>"-1"]);    
            }
            return $this->ReSucess($result);	
        } catch (\Exception $e) {
            return $this->ReError($e->getMessage());
        }
    }
    
	 
	/**
	* 毛利报表主页
	* /appadmin/v1/shop/reportIndex
	* 需要登录 
	* @is_need_login true
	* @method post
	*/
	public function reportIndex($type=1,$shop_id=-1){
		$shop_id = $shop_id == -1 ? request()->shopId  : $shop_id;
		try {
			$t = 'today';
			if( $type == 2 ) $t = 'month';
			if( $type == 3 ) $t = 'year';
			
			$prices = model('order')
					->where('shop_id',$shop_id)
					->whereTime('add_time',$t)
					->field("ifnull(sum(total_cost_price + freight_price),0)  cost")
					->field("ifnull(sum(pay_price),0) as sl")
					->field("ifnull(sum(pay_price) - sum(total_cost_price + freight_price),0) as ml")
					->find();
					
			return $this->ReSucess($prices);	
			
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}
	
	
	/**
	* 大毛利报表
	* /appadmin/v1/shop/mlone
	* 需要登录 
	* @is_need_login true
	* @method post
	*/
	public function mlone($type=1,$shop_id=-1){
		$shop_id = $shop_id == -1 ? request()->shopId  : $shop_id;
		try {
			$t = 'today';
			if( $type == 2 ) $t = 'month';
			if( $type == 3 ) $t = 'year';
			
			$prices = model('order')->alias('a')
					->leftJoin('orderGoods b','a.id = b.order_id')	
					->leftJoin('goods c','b.goods_id = c.id')	
					->leftJoin('goods_cate d','d.id = c.cate_id')	
					->leftJoin('goods_cate e','e.id = d.pid')	
					->field("e.name as classify")
					->field("ifnull(sum(a.total_cost_price + a.freight_price),0)  cost")
					->field("ifnull(sum(a.pay_price),0) as yj")
					->field("ifnull(sum(a.pay_price) - sum(a.total_cost_price + a.freight_price),0) as ml")
					->wherenotnull('e.name')
					->where('a.shop_id',$shop_id)
					->whereTime('a.add_time',$t)
					->page(input('pageIndex') ?: 1,input('pageSize') ?: 20)
					->group('e.id')	
					->select();
					
			return $this->ReSucess($prices);	
			
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}


	/**
	* 子毛利报表
	* /appadmin/v1/shop/mltwo
	* 需要登录 
	* @is_need_login true
	* @method post
	*/
	public function mltwo($type=1,$shop_id=-1){
		$shop_id = $shop_id == -1 ? request()->shopId  : $shop_id;
		try {
			$t = 'today';
			if( $type == 2 ) $t = 'month';
			if( $type == 3 ) $t = 'year';
			
			$prices = model('order')->alias('a')
					->leftJoin('orderGoods b','a.id = b.order_id')	
					->leftJoin('goods c','b.goods_id = c.id')	
					->leftJoin('goods_cate d','d.id = c.cate_id')	
					->leftJoin('goods_cate e','e.id = d.pid')	
					->field("concat(e.name,'-',d.name) as classify")
					->field("ifnull(sum(a.total_cost_price + a.freight_price),0)  cost")
					->field("ifnull(sum(a.pay_price),0) as yj")
					->field("ifnull(sum(a.pay_price) - sum(a.total_cost_price + a.freight_price),0) as ml")
					->wherenotnull('e.name')
					->where('a.shop_id',$shop_id)
					->whereTime('a.add_time',$t)
					->page(input('pageIndex') ?: 1,input('pageSize') ?: 20)
					->group('d.id')	
					->select();
					
			return $this->ReSucess($prices);	
			
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}
	
	
	/**
	* 我的店铺
	* /appadmin/v1/shop/myShop
	* 需要登录 
	* @is_need_login true
	*/
	public function myShop(){
		try {
			$result = model('Shop')->alias('a')
				->leftJoin("(
					select shop_id,sum(number) ljsr from xw_shop_bill 
					where category = 'balance' and pm =1 and status = 1 and type != 'extract_reject'
					group by shop_id
				) b",'a.id = b.shop_id')
				->where('a.id', $this->request ->shopId )
				->field('a.id,(a.balance - a.lock_balance) as balance')
				->field('ifnull(b.ljsr,0) ljsr')
				->findOrEmpty();
				
			$result['min_extract']	= getSystem("buess_shop_extract_min");
			$result['min_recharge']	= getSystem("buess_shop_min_recharge");
			$result['extract_cost']	= getSystem("buess_shop_extract_cost").'%';
				
			return $this->ReSucess($result);	
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}
	
	/**
	* 店铺充值-获取支付签名
	* /appadmin/v1/shop/recharge
	* 是否需要登录 
	* @is_need_login true
	*/
	public function recharge($price,$mode="h5"){
		if( $this->request->identity != 2 ){
        	return $this->ReError('店长才有权限操作！' );
    	}
		if( !$price ){
			return $this->ReError('参数错误！');	
		}
		if( $price < $minRecharge =  (getSystem("buess_shop_min_recharge") ?: 0) ){
			return $this->ReError('最少充值'.$minRecharge.'元!');	
		}
		
		$openid = $this->request->wxInfo['openid'];
		
		try {
			
			if( !$shop = model('shop')->get( $this->request->shopId) ){
				return $this->ReError('异常错误！');	
			}
			
			$wxapi = new WxApi($mode);
			$db = model("ShopRecharge");
			$order = $db->where('status',0)->where('price',$price)->order("add_time desc")->limit(1)->find();
			if( $order && !$wxapi->orderQuery($order->no) ){
				$order->add_time=date("Y-m-d H:i:s");
				$order->save();
			}else{
				$order = $db->add( ['price'=>$price,'shop_id'=>$shop->id ] );
			}
			
			$paySign = $wxapi->createOrder($order->no,$order->price,$openid);
			
			return $this->ReSucess(compact('order', 'paySign'));	
			
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}
	
	/**
	* 店铺充值-获取充值状态
	* /appadmin/v1/shop/rechargeStatus
	* 是否需要登录 
	* @is_need_login true
	*/
	public function rechargeStatus(){
		if(request()->identity != 2){
        	return $this->ReError('店长才有权限操作！' );
    	}
		try {
			$status = model("ShopRecharge")->getRechargeStatus(request() ->shopId);
			return $this->ReSucess($status);	
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}
	
	
	/**
	* 店铺消费记录
	* /appadmin/v1/shop/myConsumeBill
	* 是否需要登录 
	* @is_need_login true
	*/
	public function myConsumeBill($type='*'){
		if($this->request->identity != 2){
        	return $this->ReError('店长才有权限操作！' );
    	}
		$shopId = $this->request ->shopId;
		try {
			$list = model('ShopBill')->billList($shopId,$type);
			return $this->ReSucess($list);	
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}
	
	
	/**
	* 店铺申请提现
	* /appadmin/v1/shop/withdraw
	* 是否需要登录 
	* @is_need_login true
	* @method post 
	*/
	public function withdraw(){
		try {
			$request =  request();
         	$result = model('ShopExtract')->shopExtract($request->shopId,$request->post());
			return $this->ReSucess($result);	
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}
	
	/**
	* 获取店铺提现记录
	* /appadmin/v1/shop/withdrawLog
	* 是否需要登录 
	* @is_need_login true
	* @method post 
	*/
	public function withdrawLog($pageIndex=1,$pageSize=20){
		$shopId = request() ->shopId;
		try {
			//TODO 提现列表
	        $extractList = model('ShopExtract')->extractList($shopId,$pageIndex,$pageSize);
			//TODO 累积已提现
	        $extractSum =  model('ShopExtract')->extractSum($shopId);
			//TODO 获得用户提现总金额-不论成败
	        $extractTotal =  model('ShopExtract')->userExtractTotalPrice($shopId);
			//----
			return $this->ReSucess(compact('extractList','extractSum','extractTotal') );	
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}
	
}



